<template>
  <div class="content-box">
    <e-heading>{{title}}</e-heading>
    <div class="set_template">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="模板名称：" required prop="temName" :rules="{ required: true, message: '模板名称最少必须由1个字组成，最多不能超过30个字'}">
          <el-input v-model="form.temName" :minlength="1" :maxlength="30" number-word style="width:85%;"></el-input>
        </el-form-item>
      <e-heading grade="2">教案（每课时）填写项</e-heading>
        <!--教学信息-->
        <el-row>
          <el-col :span="24">
            <el-checkbox v-model="form.information.value" @change="handleChangeSet(form.information)">{{form.information.name}}</el-checkbox>
          </el-col>
        </el-row>
        <div class="tem_cont">
          <el-row v-for="(item, index) in form.information.list" :key="index" v-if="!item.isUserPush">
            <el-col v-if="item.isUserSet">
              <div class="user_set">
                <custom-add-item
                  v-if="editState"
                  v-model="item.customGroupValue"
                  :isEdit="isEdit"
                  :span="12"
                  :simple-layout="true"
                  :fixedData="item.list"
                  :max-item="item.MAX_CUSTOM_GROUP_NUM"
                  :editState="form.information.value"
                  :maxlength="item.maxlength"
                  repeatTipText="自定义项名称不能重复"
                  :placeholder="item.placeholder"
                  @change="handleCustomAddInput(item, 'info')"/>
              </div>
            </el-col>
            <el-col :span="item.list ? 3 : 24" v-else>
              <el-checkbox v-model="item.value" :checked="item.value" v-if="!item.isUserPush" :disabled="!form.information.value" @change="handleChangeData(form.information, item)">{{item.name + (item.maxLength ? '(可输入' + item.maxLength + '字）' : '')}}</el-checkbox>
            </el-col>
            <el-col :span="item.list ? 20 : 0" v-if="!item.isCode">
              <el-row v-for="(sitem, sindex) in item.list" :key="sindex">
                <el-col :span="3">
                  <el-checkbox v-model="sitem.value" :disabled="!item.value || !form.information.value" style="min-width:50px;" @change="handleChangeData(item, sitem)">{{sitem.name}}</el-checkbox>
                </el-col>
                <el-col :span="21">
                  <el-checkbox-group v-model="sitem.listValue" size="small" class="checker-plain" v-if="!sitem.nolist">
                    <el-checkbox-button v-for="(titem, tindex) in sitem.list" :key="tindex" :label="titem" :disabled="!form.information.value || !item.value || !sitem.value" @change="handleChangeValue(sitem, titem)">{{titem}}</el-checkbox-button>
                  </el-checkbox-group>
                  <div class="user_set">
                    <custom-add-item
                      v-if="sitem.isSet && editState"
                      v-model="sitem.customGroupValue"
                      :isEdit="isEdit"
                      :span="12"
                      :simple-layout="true"
                      :fixedData="sitem.list"
                      :max-item="sitem.MAX_CUSTOM_GROUP_NUM"
                      :editState="item.value && form.information.value && sitem.value"
                      :maxlength="sitem.maxlength"
                      repeatTipText="自定义项名称不能重复"
                      :placeholder="sitem.placeholder"
                      @change="handleCustomAddChange(sitem)"/>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="item.list ? 20 : 0" v-else>
              <el-checkbox-group v-model="item.listValue" size="small" class="checker-plain">
                 <el-checkbox-button v-for="(sitem, sindex) in item.list" :key="sindex" :label="sitem" :disabled="!form.information.value || !item.value" @change="handleChangeValue(item, sitem)">{{sitem}}</el-checkbox-button>
              </el-checkbox-group>
              <div class="user_set">
                <custom-add-item
                  v-if="item.isSet && editState"
                  v-model="item.customGroupValue"
                  :isEdit="isEdit"
                  :span="12"
                  :simple-layout="true"
                  :fixedData="item.list"
                  :max-item="item.MAX_CUSTOM_GROUP_NUM"
                  :editState="form.information.value && item.value"
                  :maxlength="item.maxlength"
                  repeatTipText="自定义项名称不能重复"
                  :placeholder="item.placeholder"
                  @change="handleCustomAddChange(item)"/>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--教学过程-->
        <el-row>
          <el-col :span="24">
            <el-checkbox v-model="form.cuurse.value" disabled>{{form.cuurse.name}}</el-checkbox>
          </el-col>
        </el-row>
        <div class="tem_cont">
          <el-row v-for="(item, index) in form.cuurse.list" :key="index" v-if="!item.isUserPush">
            <el-col :span="24" v-if="item.isUserSet">
              <div class="user_set">
                <custom-add-item
                  v-if="item.isSet && editState"
                  v-model="item.customGroupValue"
                  :isEdit="isEdit"
                  :span="12"
                  :simple-layout="true"
                  :fixedData="item.list"
                  :max-item="item.MAX_CUSTOM_GROUP_NUM"
                  :editState="item.editState"
                  :maxlength="item.maxlength"
                  repeatTipText="自定义项名称不能重复"
                  :placeholder="item.placeholder"
                  @change="handleCustomAddInput(item, 'course')"/>
              </div>
            </el-col>
            <el-col :span="24" v-else>
              <el-checkbox v-model="item.value" :disabled="!form.cuurse.value || item.name == '预计时长：'" v-if="!item.isUserPush" @change="handleChangeData(form.cuurse, item)">{{item.name + (item.maxLength ? '(可输入' + item.maxLength + '字）' : '')}}</el-checkbox>
            </el-col>
          </el-row>
        </div>
        <!--课后小节-->
        <el-row>
          <el-col :span="24">
            <el-checkbox v-model="form.summary.value">{{form.summary.name + (form.summary.maxLength ? '(可输入' + form.summary.maxLength + '字）' : '')}}</el-checkbox>
          </el-col>
        </el-row>
      </el-form>
      <div class="button-box">
        <el-button @click="handlePreview()">预 览</el-button>
        <el-button type="primary" @click="submit()">保 存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import trainApi from 'api/train'
import CustomAddItem from '../../service/components/CustomAddItem'
export default {
  components: {
    CustomAddItem
  },
  created () {
    if (this.$route.query.state === 'edit') {
      this.isEdit = true
      trainApi.getTemData({
        id: Number(this.$route.query.tempId)
      }).then((res) => {
        this.form.temName = res.data.templateName
        this.form.information = JSON.parse(res.data.teachInfo)
        this.form.cuurse = JSON.parse(res.data.teachProcess)
        this.form.summary = JSON.parse(res.data.teachSummary)
        this.editState = true
      })
    } else {
      this.editState = true
    }
  },
  data () {
    return {
      title: '设置教案模板',
      isEdit: false,
      infoData: [],
      curData: [],
      editState: false,
      form: {
        temName: '',
        information: {
          name: '教学信息',
          value: true,
          list: [
            {
              name: '教学目标：', // name
              type: 'textarea', // 表单类型
              placeholder: '例如：\n1、培养学生的身体协调性和节奏感；\n2、提高学生的弹跳能力；\n3、培养学生不惧困难、敢于展示自我，学会与他人合作的良好社会适应能力，提高自信，培养创新意识。',
              maxLength: 200,
              isSet: false, // 是否有自定义
              isCode: true, // 是否是只有一级分组
              value: true, // 模板字段是否选中
              valueData: '', // 模板字段值
              list: []
            },
            {
              name: '重点领域：',
              type: 'checkbox',
              isSet: true,
              isCode: true,
              value: true,
              checkType: 'button',
              valueData: [],
              listValue: ['课堂参与', '技能培训', '身体素质', '心理健康'], // 选中字段选项值
              list: ['课堂参与', '技能培训', '身体素质', '心理健康'],
              customGroupValue: [], // 自定义项值
              MAX_CUSTOM_GROUP_NUM: 10,
              maxlength: 20, // 输入框文本长度
              placeholder: '自定义重点领域'
            },
            {
              name: '场地器材：',
              type: 'checkbox',
              isSet: false,
              isCode: false,
              value: true,
              list: [
                {
                  name: '场地',
                  type: 'checkbox',
                  isSet: true,
                  isCode: true,
                  value: true,
                  valueData: [],
                  listValue: ['教室', '球场', '球馆'],
                  list: ['教室', '球场', '球馆'], // 默认值
                  customGroupValue: [], // 自定义项值
                  MAX_CUSTOM_GROUP_NUM: 10,
                  maxlength: 20, // 输入框文本长度
                  placeholder: '自定义场地'
                },
                {
                  name: '器材',
                  type: 'checkbox',
                  isSet: true,
                  isCode: true,
                  value: true,
                  valueData: [],
                  listValue: ['口哨', '足球', '篮球', '网球/网球拍', '羽毛球/羽毛球拍', '乒乓球/乒乓球拍'],
                  list: ['口哨', '足球', '篮球', '网球/网球拍', '羽毛球/羽毛球拍', '乒乓球/乒乓球拍'],
                  customGroupValue: [], // 自定义项值
                  MAX_CUSTOM_GROUP_NUM: 10,
                  maxlength: 20, // 输入框文本长度
                  placeholder: '自定义器材'
                }
              ]
            },
            {
              name: '负荷预计：',
              type: '',
              value: true,
              isSet: false,
              isCode: false,
              listValue: [],
              list: [
                {
                  name: '平均心率',
                  type: 'number',
                  prop: 'heartRate',
                  value: true,
                  valueData: '',
                  unit: '次/分'
                },
                {
                  name: '练习密度',
                  type: 'number',
                  prop: 'intension',
                  value: true,
                  unit: '%',
                  remark: '(练习密度是指课中各项教学活动合理运用的时间与上课的总时间的比例)',
                  valueData: ''
                },
                {
                  name: '心理负荷',
                  type: 'radio',
                  value: true,
                  valueData: '',
                  nolist: true,
                  list: ['弱', '较弱', '中等', '较强', '强']
                }
              ]
            },
            {
              name: '自定义（可输入500字）',
              value: false,
              isSet: true,
              isUserSet: true,
              isCode: false,
              list: [],
              customGroupValue: [], // 自定义项值
              MAX_CUSTOM_GROUP_NUM: 10,
              maxlength: 20, // 输入框文本长度
              placeholder: '自定义教学信息(500字)'
            }
          ]
        },
        cuurse: {
          name: '教学过程',
          value: true,
          list: [
            {
              name: '教学内容与方法措施：',
              type: 'textarea', // 表单类型
              placeholder: '例如：课堂常规讲解、热身运动、基本体操等\n1、队长集合整队并报告人数\n2、师生问好\n3、检查服装和器材\n4、宣布本课内容及要求',
              maxLength: 200,
              isCode: true,
              value: true,
              valueData: ''
            },
            {
              name: '预计时长：',
              type: 'number',
              isCode: true,
              prop: 'time',
              value: true,
              valueData: '',
              unit: '分钟'
            },
            {
              name: '训练次数：',
              type: 'number',
              isCode: true,
              prop: 'count',
              value: true,
              valueData: '',
              unit: '次'
            },
            {
              name: '预计问题与处理方法：',
              type: 'textarea', // 表单类型
              isCode: true,
              placeholder: '例如：预计问题：部分学生模仿不像\n处理方法：教练加强引导练习',
              maxLength: 200,
              value: true,
              valueData: ''
            },
            {
              name: '组织形式、场地布置：',
              type: 'setRadio',
              isCode: true,
              value: true,
              valueData: ''
            },
            {
              name: '自定义（可输入500字）',
              value: false,
              isSet: true,
              isUserSet: true,
              isCode: false,
              list: [],
              customGroupValue: [], // 自定义项值
              MAX_CUSTOM_GROUP_NUM: 10,
              maxlength: 20, // 输入框文本长度
              placeholder: '自定义教学过程(500字)'
            }
          ]
        },
        summary: {
          name: ' 课后小结：',
          type: 'textarea', // 表单类型
          isCode: true,
          placeholder: '例如：课堂常规讲解、热身运动、基本体操等',
          maxLength: 200,
          value: true,
          valueData: ''
        }
      }
    }
  },
  methods: {
    handleCustomAddChange (data) {
      let setArr = data.customGroupValue
      let checkArr = []
      let defaultArr = []
      let selectArr = []
      for (let item of data.listValue) {
        if (data.list.includes(item)) {
          defaultArr.push(item)
        }
      }
      for (let item of setArr) {
        if (item.checked) {
          selectArr.push(item.name)
          checkArr.push(item)
        }
      }
      data.listValue = defaultArr.concat(selectArr)
      data.customGroupValue = checkArr
      if (defaultArr.length === 0 && selectArr.length === 0) {
        data.value = false
      }
    },
    submit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let data = this.getSubData()
          let type = this.$route.query.state ? 'edit' : ''
          trainApi.insertTemplate({
            id: this.$route.query.tempId ? Number(this.$route.query.tempId) : '',
            templateName: data.temName,
            teachInfo: JSON.stringify(data.information),
            teachProcess: JSON.stringify(data.cuurse),
            teachSummary: JSON.stringify(data.summary)
          }, type).then((res) => {
            this.$router.go(-1)
          })
        } else {
          return false
        }
      })
    },
    getSubData () {
      let setData = JSON.parse(JSON.stringify(this.form))
      setData.information.list = setData.information.list.concat(this.infoData)
      setData.cuurse.list = setData.cuurse.list.concat(this.curData)
      return setData
    },
    handlePreview () {
      localStorage.setItem('tem_data', JSON.stringify(this.getSubData()))
      window.open('/training/curriculum/previewTem')
    },
    handleChangeSet (data) {
      if (data.value === true) {
        for (let item of data.list) {
          if (typeof item !== 'string' && !item.isUserSet) {
            this.$set(item, 'value', true)
            this.handleChangeData(data, item)
          }
        }
      }
    },
    handleChangeData (data, thisData) {
      if (thisData.value === true && thisData.list) {
        for (let item of thisData.list) {
          if (typeof item !== 'string') {
            this.$set(item, 'value', true)
            this.$set(item, 'listValue', item.list)
          }
        }
        this.$set(thisData, 'listValue', thisData.list)
      }
      let isShow = []
      for (let i = 0; i < data.list.length; i++) {
        if (data.list[i].value) {
          isShow.push(true)
        } else {
          isShow.push(false)
        }
      }
      if (isShow.includes(true)) {
        this.$set(data, 'value', true)
      } else {
        this.$set(data, 'value', false)
      }
    },
    handleChangeValue (item, thisData) {
      if (item.listValue.length > 0) {
        this.$set(item, 'value', true)
      } else {
        this.$set(item, 'value', false)
      }
    },
    handleCustomAddInput (data, type) {
      let setArr = data.customGroupValue
      let checkArr = []
      let getArr = []
      if (type === 'info') {
        for (let i = 0; i < this.form.information.list.length; i++) {
          if (this.form.information.list[i].isUserPush) {
            this.form.information.list.splice(i--, 1)
          }
        }
      } else {
        for (let i = 0; i < this.form.cuurse.list.length; i++) {
          if (this.form.cuurse.list[i].isUserPush) {
            this.form.cuurse.list.splice(i--, 1)
          }
        }
      }
      for (let item of setArr) {
        if (item.checked) {
          getArr.push({
            name: item.name + '：', // name
            isUserPush: true,
            type: 'textarea', // 表单类型
            placeholder: '请输入' + item.name,
            maxLength: 500,
            value: true,
            isCode: true, // 是否是只有一级分组
            valueData: '' // 模板字段值
          })
          checkArr.push(item)
        }
      }
      data.customGroupValue = checkArr
      type === 'info' ? this.infoData = getArr : this.curData = getArr
    }
  }
}
</script>

<style lang="scss">
 
.set_template{
  .checker-plain{
    display: inline-block;
  }
  .el-checkbox-button{
    margin:0 3px 8px 3px;
     .el-checkbox-button__inner{
      border-radius: 3px;
      border-left: 1px solid #e3e3ec; 
      box-shadow:none;
      -webkit-box-shadow:none;
    }
  }
  .el-checkbox-button:first-child .el-checkbox-button__inner, .el-checkbox-button:last-child .el-checkbox-button__inner{
     border-radius: 3px;
  }
  .tem_title{
    position: relative;
    border-bottom:1px solid #eee;
    height:38px;
    font-size: 16px;
    margin:0 0 35px 0;
    span{
      position: absolute;
      line-height: 36px;
      border-bottom:2px solid $color-primary;
    }
  }
  .tem_cont{
    padding:15px 25px;
    margin-top:5px;
    background: #fafafa;
    margin-bottom: 30px;
    .el-row{
      margin:0 0 8px 0;
      line-height: 40px;
    }
  }
  .user_set{
    margin-top:8px;
    .custom-group-wrapper{
      .err-tips-wrapper{
        left: -60%;
      }
      .xcheckbox-item{
        position: relative;
        display: inline;
        .xsmall {
          width:95%;
          &.input-small{
            margin-left: 4px;
          }
          &.inputs-small{
            width: 75px;
          }
        }
      }
    }
  }
  .temclass_list{
    border:1px solid #efefe3;
    padding:25px;
    .el-checkbox-group{
      margin-top: 7px;
    }
    .el-checkbox-group .el-checkbox{
      width:48%;
      margin-right:2%;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .el-checkbox{
      line-height: 2;
    }
  }
}
</style>
